import Reflux from 'reflux';
import Actions from "./Actions";
import update from 'react-addons-update';
import {Control} from "react-keeper";
import DB from '../../../../../app/db';
import StorageUtils from "../../../../../app/storage";
import Utils from "../../../../../utils/index";
import {RwCode, getInfoByOpenId} from "../../const/Const";
import {Toast} from "antd-mobile";

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    userInfo: {},
    rw: {}
  },

  initRw() {
    this.data.userInfo = update(this.data.userInfo, {$set: StorageUtils.getUser()});
    this.updateComponent();
    this.data.rw = update(this.data.rw, {$set: Control.state});
    this.updateComponent();
  },

  doYwhTp(data) {
    let t = this;
    let myDoors = StorageUtils.getStorageItem('doors');
    if (Utils.arrayIsNotEmpty(myDoors)) {
      myDoors.map(door => {
        let params;
        switch (t.data.rw.rwCode) {
          case RwCode.CAST01:
            if (door.courtId === data.courtId && door.building === data.building && door.unit === data.unit) {
              params = {
                doorId: data.id,
                selfDoorplateid: door.id,
                rwCode: RwCode.CAST01
              }
            }
            break;
          case RwCode.CAST02:
            if (door.courtId === data.courtId && door.building === data.building) {
              params = {
                doorId: data.id,
                selfDoorplateid: door.id,
                rwCode: RwCode.CAST02
              }
            }
            break;
          case RwCode.CAST03:
            if (door.courtId === data.courtId) {
              params = {
                doorId: data.id,
                selfDoorplateid: door.id,
                rwCode: RwCode.CAST03
              }
            }
            break;
          case RwCode.CAST04:
            if (door.courtId === data.courtId) {
              params = {
                doorId: data.id,
                selfDoorplateid: door.id,
                rwCode: RwCode.CAST04
              }
            }
            break;
          default:
            break;
        }

        if (params) {
          DB.ywh.ywhTp(params).then(
            function (content) {
              t.data.rw.isVoted = update(t.data.rw.isVoted, {$set: true});
              t.updateComponent();
              Toast.success('投票成功');
              getInfoByOpenId(t.data.userInfo.openId);
            },
            function (error) {
            }
          );
        }
      })
    }
  },

  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState() {
    return this.data;
  }
});
